<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\DrainageLink\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Logger\LoggerFactory;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\User\Contract\UserContract;
use MoChat\App\Utils\Url;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ChannelCode\Contract\ChannelCodeContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContract;

/**
 * 引流链接-列表.
 *
 * Class Index.
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var DrainageLinkContract
     */
    protected $drainageLink;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userService;

    /**
     * @Inject
     * @var ChannelCodeContract
     */
    protected $channelCode;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    /**
     * @var int 企业id
     */
    private $corpId;

    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('drainageLink');
    }

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/drainageLink/index", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 获取当前登录用户
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 验证参数
        $this->validated($this->request->all());
        // 接收参数
        $params = [
            'type' => (int) $this->request->input('type'),
            'name' => $this->request->input('name', ''),
            'page' => (int) $this->request->input('page', 1),
            'perPage' => (int) $this->request->input('perPage', 10),
        ];

        // 组织查询条件
        $where['corp_id'] = $user['corpIds'][0];
        $where['type'] = $params['type'];
        empty($params['name']) || $where[] = ['name', 'LIKE', '%' . $params['name'] . '%'];
        $options = [
            'page' => $params['page'],
            'perPage' => $params['perPage'],
            'orderByRaw' => 'id desc',
        ];
        // 查询字段
        $columns = ['id', 'name', 'qrcode_type', 'qrcode', 'qrcode_id', 'creator_id', 'created_at'];

        $res = $this->drainageLink->getDrainageLinkList($where, $columns, $options);

        // 组织响应数据
        $data = [
            'page' => [
                'perPage' => $params['perPage'],
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];

        if (empty($res['data'])) {
            return $data;
        }

        // 处理分页数据
        $data['page']['total'] = $res['total'];
        $data['page']['totalPage'] = $res['last_page'];
        $data['list'] = $this->handleData($res['data'], $params);
        return $data;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.required' => '类型 必传',
        ];
    }

    private function handleData(array $list, array $params): array
    {
        foreach ($list as $k => $v) {
            if ($params['type'] === 1 && $v['qrcodeType'] === 2) {
                $channelCode = $this->channelCode->getChannelCodeByIdWithTrashed($v['qrcodeId'], ['name', 'qrcode_url']);
                $list[$k]['qrcodeName'] = $channelCode['name'];
                $list[$k]['qrcode'] = file_full_url($channelCode['qrcodeUrl']);
            }
            if ($params['type'] === 1 && $v['qrcodeType'] === 1) {
                $list[$k]['qrcode'] = file_full_url($v['qrcode']);
            }
            $username = $this->userService->getUserById($v['creatorId']);
            $list[$k]['creatorId'] = $username['name'] ?? '';
            $list[$k]['link'] = $this->generateShortUrl(Url::getOperationBaseUrl() . '/drainageLink?id=' . $v['id']);
        }
        return $list;
    }

    /**
     * 生成短网址
     */
    private function generateShortUrl(string $url): string
    {
        return $url;
    }
}
